# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=mopac
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=23.1.2
pkgrel=1
pkgdesc="Molecular Orbital PACkage. (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='http://openmopac.net'
msys2_repository_url='https://github.com/openmopac/mopac'
license=('spdx:Apache-2.0')
depends=($([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran")
         "${MINGW_PACKAGE_PREFIX}-omp"
         "${MINGW_PACKAGE_PREFIX}-openblas")
makedepends=("${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
checkdepends=("${MINGW_PACKAGE_PREFIX}-python"
              "${MINGW_PACKAGE_PREFIX}-python-numpy")
source=("https://github.com/openmopac/mopac/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "0001-Fix-installing-library.patch")
sha256sums=('60436bbf62045f06f17b4604bf241c8c6359a70a89c41d00913833bf32ea0121'
            '311b4224e04a109ff4f073254a0a716c1989e035bbeeb7033f9d61c0208419e5')

prepare() {
  cd "${_realname}-${pkgver}"

  patch -Np1 -i "${srcdir}"/0001-Fix-installing-library.patch
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    extra_config+=("-DTHREADS_KEYWORD=OFF")
  else
    extra_config+=("-DTHREADS_KEYWORD=ON")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -G"MSYS Makefiles" \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -DF2003_INTRINSICS=ON \
      -DENABLE_MKL=OFF \
      -DGIT_HASH=OFF \
      -DTESTS=OFF \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"
}

check() {
  cmake \
    -DTESTS=ON \
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python \
    -S "${_realname}-${pkgver}" \
    -B "build-${MSYSTEM}"
  cmake  --build "build-${MSYSTEM}"

  ctest --test-dir build-${MSYSTEM} --output-on-failure
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}" --component redist

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
  rm "${pkgdir}"${MINGW_PREFIX}/include/LICENSE
  rm "${pkgdir}"${MINGW_PREFIX}/LICENSE

  mkdir -p "${pkgdir}"${MINGW_PREFIX}/share/doc/${_realname}
  mv "${pkgdir}"${MINGW_PREFIX}/CITATION.cff "${pkgdir}"${MINGW_PREFIX}/share/doc/${_realname}/
}
